from django.shortcuts import render
from django.shortcuts import get_object_or_404
from polls.models import Question, Choice
from django.template import loader
from django.http import HttpResponse
from django.http import Http404
from django.http import HttpResponseRedirect
from django.urls import reverse


# Create your views here.
def index(request):
    # 方案一
    # questions = Question.objects.all()[:5]
    # template = loader.get_template('polls/index.html')
    # context = {'questions': questions}
    # return HttpResponse(template.render(context, request))

    # 方案二
    questions = Question.objects.all()
    context = {'questions': questions}
    return render(request, 'polls/index.html', context)


def detail(request, question_id):
    # 方案一， 问题对应的选项查询出来传递给页面模板
    # question = Question.objects.get(pk=question_id)
    # choices = Choice.objects.filter(question=question)
    # context = {'question': question, 'choices': choices}

    try:
        # 方案二，使用Try except 捕获异常，同时view试图中不获取问题选项，而使用 question.choices_set.al 来在模板渲染中获取
        question = Question.objects.get(pk=question_id)
        context = {'question': question}
    except Question.DoesNotExist:
        raise Http404('Question dose not exist')

    return render(request, 'polls/detail.html', context)


def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    context = {'question': question}
    return render(request, 'polls/result.html', context)


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    # 知识点: 如果想多个错误类型返回相同信息的时候，可以使用括号
    except (KeyError, Choice.DoesNotExist):
        context = {'error_message': 'You did not select a choice', 'question': question}
        return render(request, 'polls/detail.html', context)
    # 知识点: try...except...else 组合使用
    else:
        # 投一次票，votes 数量加1
        selected_choice.votes += 1
        selected_choice.save()
        # 知识点: reverse 根据path-name转化成具体的路径，可以带参数，比如如下转化成 /polls/xx/result/
        # 然后 HttpResponseRedirect 是发起Http相应的redirect跳转
        # 也就是在 问题详情页点击投票，进行投票逻辑处理之后，跳转到该问题的 统计结果页面去
        return HttpResponseRedirect(reverse('polls:polls-result', args=(question.id, )))
